package liumengbaio.lolzhangyoubao.Activity.Fragment;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

import liumengbaio.lolzhangyoubao.Activity.Activity.HeroManitoActivity;
import liumengbaio.lolzhangyoubao.Activity.Adapter.HeroDataAdapter;
import liumengbaio.lolzhangyoubao.Activity.InFo.FreeHeroInfo;
import liumengbaio.lolzhangyoubao.Activity.InFo.HeroDataListViewInfo;
import liumengbaio.lolzhangyoubao.Activity.InFo.HeroDataOneInfo;
import liumengbaio.lolzhangyoubao.Activity.InFo.HeroDataTwoInfo;
import liumengbaio.lolzhangyoubao.Activity.utils.AssetsUtils;
import liumengbaio.lolzhangyoubao.Activity.utils.HttpUtils;
import liumengbaio.lolzhangyoubao.R;

/**
 * Created by lanouhn on 16/8/23.
 */
public class FragmentHeroData extends Fragment {
    private TextView tv_rank, tv_winchance, tv_kda, tv_usermost, tv_usernumber, tv_userwinchance, tv_winchancemost, tv_winuserchance, tv_winmostchance;
    private ImageView iv_first, iv_second, iv_third, iv_fourth, iv_fifth, iv_sixth, iv_win_first, iv_win_second, iv_win_third, iv_win_fourth, iv_win_fifth, iv_win_sixth;
    private HeroDataOneInfo mHeroDataOneInfo;
    private HeroDataTwoInfo mHeroDataTwoInfo;
    private ListView heroDataListView;
    private HeroDataListViewInfo listViewInfo;
    private HeroDataAdapter heroDataAdapter;

    private LinearLayout ll_lookformore;

    AssetManager assets = null;


    public static FragmentHeroData newInstants(FreeHeroInfo info) {
        FragmentHeroData fragmentHeroData = new FragmentHeroData();
        Bundle bundle = new Bundle();
        bundle.putSerializable("datainfo", info);
        fragmentHeroData.setArguments(bundle);
        return fragmentHeroData;
    }

    String id,userid;
    String newFirstStr,newSecondStr,newThirdStr,newFourthStr,newFifthStr,newSixthStr;
    String newWinFirstStr,newWinSecondStr,newWinThirdStr,newWinFourthStr,newWinFifthStr,newWinSixthStr;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_herodata, null);
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(getView());
        initData();
        getDatafromWeb();
    }


    private void initView(View view) {
        heroDataListView= (ListView) view.findViewById(R.id.data_listview);
        ll_lookformore= (LinearLayout) view.findViewById(R.id.ll_lookformore);
        tv_rank = (TextView) view.findViewById(R.id.tv_rank);
        tv_winchance = (TextView) view.findViewById(R.id.tv_winchance);
        tv_kda = (TextView) view.findViewById(R.id.tv_kda);
        tv_usermost = (TextView) view.findViewById(R.id.tv_usermost);
        tv_usernumber = (TextView) view.findViewById(R.id.tv_usernumber);
        tv_userwinchance = (TextView) view.findViewById(R.id.tv_user_winchance);
        tv_winchancemost = (TextView) view.findViewById(R.id.tv_winchancemost);
        tv_winuserchance = (TextView) view.findViewById(R.id.tv_winuserchance);
        tv_winmostchance = (TextView) view.findViewById(R.id.tv_winmostchance);
        iv_first = (ImageView) view.findViewById(R.id.iv_first);
        iv_second = (ImageView) view.findViewById(R.id.iv_second);
        iv_third = (ImageView) view.findViewById(R.id.iv_third);
        iv_fourth = (ImageView) view.findViewById(R.id.iv_fourth);
        iv_fifth = (ImageView) view.findViewById(R.id.iv_fifth);
        iv_sixth = (ImageView) view.findViewById(R.id.iv_sixth);
        iv_win_first = (ImageView) view.findViewById(R.id.iv_win_first);
        iv_win_second = (ImageView) view.findViewById(R.id.iv_win_second);
        iv_win_third = (ImageView) view.findViewById(R.id.iv_win_third);
        iv_win_fourth = (ImageView) view.findViewById(R.id.iv_win_fourth);
        iv_win_fifth = (ImageView) view.findViewById(R.id.iv_win_fifth);
        iv_win_sixth = (ImageView) view.findViewById(R.id.iv_win_sixth);

    }

    private void initData() {
        FreeHeroInfo herodatainfo = (FreeHeroInfo) getArguments().getSerializable("datainfo");
        id = herodatainfo.getId();
        userid = AssetsUtils.getChampion_id(getActivity(), id);
        ll_lookformore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(getActivity(), HeroManitoActivity.class);
                intent.putExtra("userid",userid);
                startActivity(intent);
            }
        });
    }


    private void getDatafromWeb() {




        String herodataurl = " http://lol.service.zhangyoubao.com/service/rest/rank.getherodata";
        String herodataurlbody = "secretSignature=as4ha5Sw2Sp2aQN1XQ3oelfb9xI%3D&game=lol&os=Android&s" +
                "ecretVersion=v1.0&params%5BchampionId%5D=" + userid + "&sign=&secretId=AKIDz8krbsJ5yKBZQpn7" +
                "4WFkmLPx3gnPhESA&deviceId=5Xot%2FXAKrRDYLof0HC98jNX5%2B4U6gHNT%2BaraufYsX04%3D&" +
                "nonce=334567&platform=Android&apiVersion=v1&osVersion=23&platformVersion=400902&ap" +
                "i=rank.getherodata&time=1473687943";
        try {
            HttpUtils.doPostAsyn(herodataurl, herodataurlbody, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    mHeroDataOneInfo = gson.fromJson(result, HeroDataOneInfo.class);
                }
            }, handler);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String mostuserurl = "http://lol.service.zhangyoubao.com/service/rest/rank.getitemrecommend";
        String mostuserurlbody = "secretSignature=a3eef499X4cXn62H4eA4TPAGyzI%3D&game=lol&os=Android&secretVersion=v1" +
                ".0&params%5BchampionId%5D=" + userid + "&sign=&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&deviceId=5Xot%2FXAKrRDYLof0HC98jNX5%2B4U6gHNT%2BaraufYsX04%3D&nonce=755500&" +
                "platform=Android&apiVersion=v1&osVersion=23&platformVersion=400902&api=rank.getitemrecommend&time=1473687943";
        try {
            HttpUtils.doPostAsyn(mostuserurl, mostuserurlbody, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson = new Gson();
                    mHeroDataTwoInfo = gson.fromJson(result, HeroDataTwoInfo.class);

                }
            }, handlertwo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String rankUrl="http://lol.service.zhangyoubao.com/service/rest/rank.getherogodlist";
        String rankBodyUrl="params%5BpageSize%5D=5&secretSignature=xjhBr4BIRea2VHagrj6UUm8M4x4%3D&game=lol&" +
                "os=Android&secretVersion=v1.0&params%5BlastId%5D=&params%5BchampionId%5D="+userid+"&sign=&secretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3gnPhESA&params%5Bversion%5D=0&deviceId=5Xot%2FXAKrRDYLof0HC98jNX5%2B4U6gHNT%2BaraufYsX04%3D&nonce=47736&platform=Android&apiVersion=v1&osVersion=23&" +
                "platformVersion=400902&api=rank.getherogodlist&time=1473748541";
        try {
            HttpUtils.doPostAsyn(rankUrl, rankBodyUrl, new HttpUtils.CallBack() {
                @Override
                public void onRequestComplete(String result) {
                    Gson gson =new Gson();
                    listViewInfo=gson.fromJson(result,HeroDataListViewInfo.class);
                }
            },handlerList);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tv_rank.setText(mHeroDataOneInfo.getData().get(0).getAppear_rank() + "");
                    tv_winchance.setText(mHeroDataOneInfo.getData().get(0).getWin_ratio() + "" + "%");
                    tv_kda.setText(mHeroDataOneInfo.getData().get(0).getKda() + "");

                    break;
                case 1:
                    Toast.makeText(getActivity(), "数据获取失败！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private Handler handlertwo = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    tv_usermost.setText(mHeroDataTwoInfo.getData().get(0).getType_desc() + "" + ":");
                    tv_usernumber.setText(mHeroDataTwoInfo.getData().get(0).getGame_count() + "");
                    tv_userwinchance.setText(mHeroDataTwoInfo.getData().get(0).getWin_rate() + "%");

                    String firstStr = mHeroDataTwoInfo.getData().get(0).getItem().get(0) + "";
                    String secondStr = mHeroDataTwoInfo.getData().get(0).getItem().get(1) + "";
                    String thirdStr = mHeroDataTwoInfo.getData().get(0).getItem().get(2) + "";
                    String fourthStr = mHeroDataTwoInfo.getData().get(0).getItem().get(3) + "";
                    String fifthStr = mHeroDataTwoInfo.getData().get(0).getItem().get(4) + "";
                    String sixthStr = mHeroDataTwoInfo.getData().get(0).getItem().get(5) + "";
                    try {
                        InputStream  is = getActivity().getAssets().open("hero/tgpIdMap.json");
                        // Read the entire asset into a local byte buffer.
                        byte[] buffer = new byte[is.available()];
                        is.read(buffer);
                        is.close();

                        // Convert the buffer into a string.
                        String text = new String(buffer, "UTF-8");
                        JSONObject hJson = new JSONObject(text);
                        newFirstStr=hJson.getString(firstStr);
                        newSecondStr=hJson.getString(secondStr);
                        newThirdStr=hJson.getString(thirdStr);
                        newFourthStr=hJson.getString(fourthStr);
                        newFifthStr=hJson.getString(fifthStr);
                        newSixthStr=hJson.getString(sixthStr);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    assets = getActivity().getAssets();

                    InputStream assetFile = null;
                    InputStream assetFileTwo = null;
                    InputStream assetFileThere = null;
                    InputStream assetFileFour = null;
                    InputStream assetFileFive = null;
                    InputStream assetFileSix = null;

                    try {

                        assetFile = assets.open("pic/" + newFirstStr + ".jpg");
                        assetFileTwo = assets.open("pic/" + newSecondStr + ".jpg");
                        assetFileThere = assets.open("pic/" + newThirdStr + ".jpg");
                        assetFileFour = assets.open("pic/" + newFourthStr + ".jpg");
                        assetFileFive = assets.open("pic/" + newFifthStr + ".jpg");
                        assetFileSix = assets.open("pic/" + newSixthStr + ".jpg");

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) iv_first.getDrawable();
                    if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) {
                        bitmapDrawable.getBitmap().recycle();
                    }
                    iv_first.setImageBitmap(BitmapFactory.decodeStream(assetFile));
                    iv_second.setImageBitmap(BitmapFactory.decodeStream(assetFileTwo));
                    iv_third.setImageBitmap(BitmapFactory.decodeStream(assetFileThere));
                    iv_fourth.setImageBitmap(BitmapFactory.decodeStream(assetFileFour));
                    iv_fifth.setImageBitmap(BitmapFactory.decodeStream(assetFileFive));
                    iv_sixth.setImageBitmap(BitmapFactory.decodeStream(assetFileSix));

                    tv_winchancemost.setText(mHeroDataTwoInfo.getData().get(1).getType_desc() + ":");
                    tv_winuserchance.setText(mHeroDataTwoInfo.getData().get(1).getGame_count() + "");
                    tv_winmostchance.setText(mHeroDataTwoInfo.getData().get(1).getWin_rate() + "%");

                    String winfirstStr = mHeroDataTwoInfo.getData().get(1).getItem().get(0) + "";
                    String winsecondStr = mHeroDataTwoInfo.getData().get(1).getItem().get(1) + "";
                    String winthirdStr = mHeroDataTwoInfo.getData().get(1).getItem().get(2) + "";
                    String winfourthStr = mHeroDataTwoInfo.getData().get(1).getItem().get(3) + "";
                    String winfifthStr = mHeroDataTwoInfo.getData().get(1).getItem().get(4) + "";
                    String winsixthStr = mHeroDataTwoInfo.getData().get(1).getItem().get(5) + "";
                    try {
                        InputStream  is = getActivity().getAssets().open("hero/tgpIdMap.json");
                        // Read the entire asset into a local byte buffer.
                        byte[] buffer = new byte[is.available()];
                        is.read(buffer);
                        is.close();

                        // Convert the buffer into a string.
                        String text = new String(buffer, "UTF-8");
                        JSONObject hJson = new JSONObject(text);
                        newWinFirstStr=hJson.getString(winfirstStr);
                        newWinSecondStr=hJson.getString(winsecondStr);
                        newWinThirdStr=hJson.getString(winthirdStr);
                        newWinFourthStr=hJson.getString(winfourthStr);
                        newWinFifthStr=hJson.getString(winfifthStr);
                        newWinSixthStr=hJson.getString(winsixthStr);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    assets = getActivity().getAssets();

                    InputStream assetFileWin = null;
                    InputStream assetFileWinTwo = null;
                    InputStream assetFileWinThere = null;
                    InputStream assetFileWinFour = null;
                    InputStream assetFileWinFive = null;
                    InputStream assetFileWinSix = null;

                    try {
                        assetFileWin = assets.open("pic/" + newWinFirstStr + ".jpg");
                        assetFileWinTwo = assets.open("pic/" + newWinSecondStr + ".jpg");
                        assetFileWinThere = assets.open("pic/" + newWinThirdStr + ".jpg");
                        assetFileWinFour = assets.open("pic/" + newWinFourthStr + ".jpg");
                        assetFileWinFive = assets.open("pic/" + newWinFifthStr + ".jpg");
                        assetFileWinSix = assets.open("pic/" + newWinSixthStr + ".jpg");

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    bitmapDrawable = (BitmapDrawable) iv_win_first.getDrawable();
                    if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()) {
                        bitmapDrawable.getBitmap().recycle();
                    }
                    iv_win_first.setImageBitmap(BitmapFactory.decodeStream(assetFileWin));
                    iv_win_second.setImageBitmap(BitmapFactory.decodeStream(assetFileWinTwo));
                    iv_win_third.setImageBitmap(BitmapFactory.decodeStream(assetFileWinThere));
                    iv_win_fourth.setImageBitmap(BitmapFactory.decodeStream(assetFileWinFour));
                    iv_win_fifth.setImageBitmap(BitmapFactory.decodeStream(assetFileWinFive));
                    iv_win_sixth.setImageBitmap(BitmapFactory.decodeStream(assetFileWinSix));

                    break;
                case 1:
                    Toast.makeText(getActivity(), "数据获取失败！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    private Handler handlerList =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    heroDataAdapter=new HeroDataAdapter(listViewInfo,getActivity());
                    heroDataListView.setAdapter(heroDataAdapter);
                    break;
                case 1:
                    Toast.makeText(getActivity(), "数据获取失败！", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };





}
